import { Tooltip } from "antd";
import { FC, PropsWithChildren, useEffect, useRef, useState } from "react";
import styled, { CSSProperties } from "styled-components";

interface EllipsisTextProps {
	style?: CSSProperties;
	className?: string | undefined;
	overlay?: string;
	rows?: number;
	showToolip?: boolean;
}
const EllipsisText: FC<PropsWithChildren<EllipsisTextProps>> = props => {
	const { children, overlay, rows = 1, showToolip = true } = props;
	const textRef = useRef<HTMLDivElement | null>(null);
	const [isOverflowing, setIsOverflowing] = useState(false);
	useEffect(() => {
		if (!textRef.current) return;
		const { clientWidth, scrollWidth, clientHeight, scrollHeight } = textRef.current;
		if (rows === 1) {
			if (scrollWidth > clientWidth) {
				setIsOverflowing(true);
			}
		} else {
			if (scrollHeight > clientHeight) {
				setIsOverflowing(true);
			}
		}
	}, [children]);
	return (
		<>
			{isOverflowing ? (
				<>
					{showToolip ? (
						<Tooltip title={overlay ?? children}>
							<EllipsisTextWrapper rows={rows} ref={textRef} {...props} />
						</Tooltip>
					) : (
						<EllipsisTextWrapper rows={rows} ref={textRef} {...props} />
					)}
				</>
			) : (
				<EllipsisTextWrapper rows={rows} ref={textRef} {...props} />
			)}
		</>
	);
};

export default EllipsisText;

const EllipsisTextWrapper = styled.div<{ rows: number }>`
	${({ rows }) =>
		rows === 1
			? `overflow: hidden;text-overflow: ellipsis;white-space: nowrap;`
			: `display: -webkit-box;
				overflow: hidden;
				-webkit-box-orient: vertical;
				line-clamp: ${rows};
				-webkit-line-clamp: ${rows};`}
`;
